import configparser
import sys
import os
import os.path as ospath
import subprocess
import time
import codecs
import shutil

pConfig=sys.argv[1]
conf = configparser.ConfigParser()
#参数1:配置文件名称
conf.readfp(codecs.open(pConfig,'r','utf-8'))
#读取配置信息
username = conf.get('info','username')
webappsPaths = conf.get('info','webappsPaths').split(',')
pwd = conf.get('info','pwd')
ips = conf.get('info','ips').split(',')
warName = conf.get('info','warName')
mvnBin = conf.get('info','mvnBin') if conf.has_option('info','mvnBin') else ''
profileId = conf.get('info','profileId')
proPath = conf.get('info','projectPath')
isFirst = conf.getboolean('info','isFirst')
openUrl = conf.get('info','openUrl')
appName=pConfig.split(".")[0]
deployDir=ospath.realpath(sys.argv[0])
if ospath.isfile(deployDir):
    deployDir=ospath.dirname(deployDir)

switchConfig=ospath.abspath(ospath.join(os.getcwd(),appName))
print('替换配置文件路径为:'+switchConfig)
revertFileObj={}
if ospath.exists(switchConfig):
    for(root,dirs,files) in os.walk(switchConfig):
        proRootPath=root.replace(switchConfig,proPath)
        for filename in files:
            filePath=ospath.join(root,filename)
            proFilePath=ospath.join(proRootPath,filename)
            print('copy:%s to %s' % (filePath,proFilePath))
            shutil.copyfile(proFilePath,filePath+'.temp')
            revertFileObj[filePath+'.temp']=proFilePath
            shutil.copyfile(filePath,proFilePath)

procMvn=subprocess.Popen(mvnBin+'mvn clean -Dmaven.test.skip=true package -P'+profileId,cwd = proPath,shell=True,stdout=subprocess.PIPE)
print(procMvn.stdout.read())
procMvn.wait()

warPath=ospath.join(proPath,'target',warName)
#恢复替换后的配置文件
for k,v in revertFileObj.items():
    shutil.copyfile(k,v)
    os.remove(k)
for i in range(len(ips)):
    ip=ips[i]
    webappsPath=webappsPaths[i]
    ipArr=ip.split(':')
    ip=ipArr[0]
    port=ipArr[1]
    pscpCmd='pscp %s %s@%s:%s' % (warPath,username,ip,ospath.join(webappsPath,appName+os.path.splitext(warName)[1]))
    print('执行命令路径:'+deployDir)
    print('上传命令：'+pscpCmd)
    proc=subprocess.Popen(pscpCmd,cwd = deployDir,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
    if isFirst:
        proc=subprocess.Popen(pscpCmd,cwd = deployDir,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
        proc.communicate('y\n')
    proc=subprocess.Popen(pscpCmd,cwd = deployDir,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
    proc.stdin.write(pwd+'\n')
    proc.stdin.flush()
    proc.wait()
    os.system('start http://%s:%s/%s/%s' % (ip,port,appName,openUrl))